#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/wait.h>

int main() {
    int fd = open("1.txt", O_RDWR);
    if(fd == -1) {
        perror("open error");
        exit(1);
    }
    
    // int* mem = mmap(NULL, 4, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    int* mem = mmap(NULL, 4, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    if(mem == MAP_FAILED) {
        perror("mmap error");
        exit(1);
    }
    
    pid_t pid = fork();

    if(pid == 0) {
        // son
        *mem = 100;
        printf("child, *mem = %d\n", *mem);
        sleep(3);
        printf("child, *mem = %d\n", *mem);
    } else if(pid > 0) {
        // parent
        sleep(1);
        printf("parent, *mem = %d\n", *mem);
        *mem = 6666;
        printf("parent, *mem = %d\n", *mem);
        wait(NULL);
    }

    munmap(mem, 4);

    close(fd);

    return 0;
}

